package com.components.headerrecycler

import android.content.Context
import android.util.AttributeSet
import androidx.recyclerview.widget.GridLayoutManager

/**
 * @Author LuoKun
 * @Des
 */
class HeaderViewGridLayoutManager : GridLayoutManager {

    private var mAdapter: HeaderViewAdapter

    constructor(
        context: Context?,
        attrs: AttributeSet?,
        defStyleAttr: Int,
        defStyleRes: Int,
        mAdapter: HeaderViewAdapter
    ) : super(context, attrs, defStyleAttr, defStyleRes) {
        this.mAdapter = mAdapter
        setSpanSizeLookup()
    }

    constructor(context: Context?, spanCount: Int, mAdapter: HeaderViewAdapter) : super(
        context,
        spanCount
    ) {
        this.mAdapter = mAdapter
        setSpanSizeLookup()
    }

    constructor(
        context: Context?,
        spanCount: Int,
        orientation: Int,
        reverseLayout: Boolean,
        mAdapter: HeaderViewAdapter
    ) : super(context, spanCount, orientation, reverseLayout) {
        this.mAdapter = mAdapter
        setSpanSizeLookup()
    }

    private fun setSpanSizeLookup() {
        super.setSpanSizeLookup(object : SpanSizeLookup() {
            override fun getSpanSize(position: Int): Int {
                return if (mAdapter != null) {
                    if (mAdapter.isHeader(position) || mAdapter.isFooter(position)) {
                        //如果是HeaderView 或者 FooterView，就让它占满一行
                        spanCount
                    } else {
                        val adjPosition = position - mAdapter.getHeadersCount()
                        this@HeaderViewGridLayoutManager.getSpanSize(adjPosition)
                    }
                } else {
                    1
                }
            }
        })
    }

    /**使外部改变普通列表项的SpanSize*/
    /**position 去掉HeaderView和FooterView后的position*/
    fun getSpanSize(position: Int): Int {
        return 1
    }

    /**不允许外部设置SpanSizeLookup*/
    override fun setSpanSizeLookup(spanSizeLookup: SpanSizeLookup?) {

    }

}